package org.hackystat.iw.projectoverviewer.page.projects;

import java.io.File;
import org.apache.wicket.markup.html.link.Link;
import org.hackystat.iw.projectoverviewer.ProjectOverviewerApplication;
import org.hackystat.iw.projectoverviewer.jaxb.projects.Projects;
import org.hackystat.iw.projectoverviewer.xml.XmlConverter;

/**
 * A link for deleting a project.
 * 
 * @author Jianfei Liao
 * @author Nathan Britton
 */
public class DeleteLink extends Link {

  /** Support serialization. */
  private static final long serialVersionUID = 1L;
  /** The name of the project to delete. */
  private final String projectName;

  /**
   * Constructor.
   * 
   * @param id Component ID, supplied by Wicket markup.
   * @param projectName The name of the project to be deleted.
   */
  public DeleteLink(String id, String projectName) {
    super(id);
    this.projectName = projectName;
  }

  /**
   * When the link is clicked, delete the project from projects instance and rewrite
   * the projects.xml file.
   */
  @Override
  public void onClick() {
    // delete the project
    ProjectOverviewerApplication app = (ProjectOverviewerApplication)getApplication();
    app.removeProject(this.projectName);
    
    // rewrite the projects.xml file
    Projects projects = app.getProjects();
    String userHome = System.getProperty("user.home");
    File file = new File(userHome + "/.hackystat/projectoverviewer/projects.xml");
    String packageName = "org.hackystat.iw.projectoverviewer.jaxb.projects";
    XmlConverter.objectToXml(projects, file, packageName);
    
    // delete the old data file if it exists
    File tm3File = 
        new File(userHome + "/.hackystat/projectoverviewer/" + this.projectName + ".tm3");
    File xmlFile = 
        new File(userHome + "/.hackystat/projectoverviewer/" + this.projectName + ".xml");
    if (tm3File.exists()) {
      tm3File.delete();
    }
    if (xmlFile.exists()) {
      xmlFile.delete();
    }
  }
  
}
